function removeq(id){
	var sm = Ext.getCmp(id).getSelectionModel();
	Ext.getCmp(id).getStore().remove(sm.getSelection());
}

function chooseCustomer(id){
	 var selectWindow=Ext.create('component.customer.selectWindow',{
 	        callbackFun: function (record) {
 	          var result=Ext.JSON.decode(record);
 	          var sm = Ext.getCmp(id).getSelectionModel();
 	          Ext.getCmp(id).getSelectionModel().getSelection()[0].set('memberName',result.customerName);
 	          Ext.getCmp(id).getSelectionModel().getSelection()[0].set('documentType',result.peDocumentType);
 	          Ext.getCmp(id).getSelectionModel().getSelection()[0].set('mobile',result.customerPhone);
 	          Ext.getCmp(id).getSelectionModel().getSelection()[0].set('documentNumber',result.peDocumentNumber);
 	        },
 	        projectId: projectId,
	 	    resourcesCode:'menu_0006_0001'
 	    });
	   selectWindow.show();
}
Ext.onReady(function(){
	   var d = new Date();
	   var str = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
	   
	   
	   var fileAttachment = Ext.create('component.file.attachment',{
           objectId: '',
           imageType: "6",
           contextPath:contextPath,
           colspan:2
      });
	   
	   var documentTypeStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data :documentType
		});
		var gridStore = Ext.create('Ext.data.Store', {
		    fields: ["memberName","documentType","documentNumber","mobile","rid"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
		        type: 'ajax',
		        url: contextPath+'/customer/familyMember/findList',
		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'},
		        extraParams:{
		        	memberType:'3',
		        	buyId:subscribeId
		        }
		    },
		    autoLoad:true
		});
		var columns_2 = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'25%'
		}, {
			text : "证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value',
           }),
           renderer: function(value,metadata,record){  
               var index = documentTypeStore.find('value',value);  
               if(index!=-1){  
                   return documentTypeStore.getAt(index).data.name;  
               }  
               return value;  
           }
		}, {
			text : "证件号码",
			dataIndex : 'documentNumber',
			width:'30%'
		},{
			text : "手机号码",
			dataIndex : 'mobile',
			width:'30%',
		}];

		var row_2=Ext.create('Ext.grid.Panel', {
			titleAlign:'left',
			title:"原共同购房者",
			minHeight:200,
			colspan:1,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore,
			columns : columns_2,
		});
		
		var gridStore4 = Ext.create('Ext.data.Store', {
		    fields: ["memberName","documentType","documentNumber","mobile"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
		        type: 'ajax',
		        url: contextPath+'/customer/subscribe/selectSubscribeCustomer',
		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'},
		        extraParams:{
		        	subscribeId:subscribeId
		        }
		    },
		    autoLoad:true
		});
		
		var columns_4 = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'25%'
		}, {
			text : "证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value',
           }),
           renderer: function(value,metadata,record){  
               var index = documentTypeStore.find('value',value);  
               if(index!=-1){  
                   return documentTypeStore.getAt(index).data.name;  
               }  
               return value;  
           }
		}, {
			text : "证件号码",
			dataIndex : 'documentNumber',
			width:'30%'
		},{
			text : "手机号码",
			dataIndex : 'mobile',
			width:'30%',
		}];

		var row_4=Ext.create('Ext.grid.Panel', {
			titleAlign:'left',
			title:"原客户信息",
			minHeight:200,
			colspan:1,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore4,
			columns : columns_4,
		});
		
		var newGridStore = Ext.create('Ext.data.Store', {
			fields: ["memberName","documentType","documentNumber","mobile"]
		});
		
		
		var columns_3 = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'25%',
			editor: {
               xtype: 'textfield'
           }
		}, {
			text : "证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value',
           }),
           renderer: function(value,metadata,record){  
               var index = documentTypeStore.find('value',value);  
               if(index!=-1){  
                   return documentTypeStore.getAt(index).data.name;  
               }  
               return value;  
           }
		}, {
			text : "证件号码",
			dataIndex : 'documentNumber',
			width:'25%',
			editor: {
				xtype: 'textfield',
	            maxLength:18
           }
		},{
			text : "手机号码",
			dataIndex : 'mobile',
			width:'25%',
			editor: {
               xtype: 'numberfield',
               hideTrigger:true
           }
		},{
		 	text:'操作',
	       	dataIndex : 'actioncolumn',
	       	renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
	            return html = '<a href="javascript:chooseCustomer(\'row3Panel\')" >选择客户</a>&nbsp;&nbsp;<a href="javascript:removeq(\'row3Panel\')">删除</a>';
	        }
       }];
		
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		
		var row_3=Ext.create('Ext.grid.Panel', {
			id:"row3Panel",
			titleAlign:'left',
			title:"新共同购房者",
			minHeight:200,
			colspan:1,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : newGridStore,
			columns : columns_3,
			plugins: [cellEditing],
			tbar:[{text:'新增',iconCls:'icon-add',
				handler:function(){
					var newCount=newGridStore.getCount();
					if(newCount>=4){
						Ext.MessageBox.alert("系统提示","新增失败，请确认新增后数量不超过4位"); 
						return;
					}
					Ext.define('record', { 
			            extend: 'Ext.data.Model', 
			            fields: ["memberName","documentType","documentNumber","mobile"]
				    });
				    var newFamilyMember  = new record(); 
				    newGridStore.insert(0, newFamilyMember);
				    cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
			}
			},{ 
            	xtype: "checkboxgroup",
            	id:"ckYbuyCustomerInfo",
            	name:"m_buyCustomerInfo",
            	items:[{
	            		boxLabel:'同原共同购房者',
	            		inputValue:'1'
	            	}
                 ],
                listeners:{
                	'change' : function(obj,ischecked){
                		var ckStatusValue = Ext.getCmp('ckYbuyCustomerInfo').getChecked();
                		var ckStatus="";
                		Ext.Array.each(ckStatusValue, function(item){
	  	        			ckStatus += item.inputValue;
	  	        		});
                		if(ckStatus==1 && gridStore.getTotalCount()>0){
    						var newCount=gridStore.getCount();
    						if(newCount>4){
    							Ext.MessageBox.alert("系统提示","同步失败，请确认同步后共同购房者数量不超过4位"); 
    							Ext.getCmp('ckYbuyCustomerInfo').items.items[0].setValue(false);
    							return;
    						}
    						var total=newGridStore.getCount()+newCount;
    						if(total>4){
    							Ext.MessageBox.alert("系统提示","新增失败，请确认新增后数量不超过4位"); 
    							Ext.getCmp('ckYbuyCustomerInfo').items.items[0].setValue(false);
    							return;
    						}
    						for(var i=0;i<gridStore.getTotalCount();i++){
    							gridStore.getAt(i).data.rid = 1;
    							newGridStore.insert(i, gridStore.getAt(i).data);
    						}
        					cellEditing.startEditByPosition({
        				        row: 0, 
        				    	column: 0
        				    });
                		}else{
                			if(gridStore.getTotalCount()==0){
                				var ckStatusValue = Ext.getCmp('ckYbuyCustomerInfo').items.items[0].checked;
                				if(ckStatusValue){
                					Ext.getCmp('ckYbuyCustomerInfo').items.items[0].setValue(false);
                				}
                				
                			}else{
                				for(var i=0;i<gridStore.getTotalCount();i++){
                    				var rid =gridStore.getAt(i).data.rid;
                    				if(rid==1){
                    					newGridStore.remove(gridStore.getAt(i));
                    				}
        						}
                			}
                		}
                	}
                }
            }
			]
		});
		var newGridStore2 = Ext.create('Ext.data.Store', {
			fields: ["memberName","documentType","documentNumber","mobile"]
		});
		var columns_5 = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'25%',
			editor: {
               xtype: 'textfield'
           }
		}, {
			text : "证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value',
           }),
           renderer: function(value,metadata,record){  
               var index = documentTypeStore.find('value',value);  
               if(index!=-1){  
                   return documentTypeStore.getAt(index).data.name;  
               }  
               return value;  
           }
		}, {
			text : "证件号码",
			dataIndex : 'documentNumber',
			width:'25%',
			editor: {
				xtype: 'textfield',
	            maxLength:18
           }
		},{
			text : "手机号码",
			dataIndex : 'mobile',
			width:'25%',
			editor: {
               xtype: 'numberfield',
               hideTrigger:true
           }
		},{
			text:'操作',
	       	dataIndex : 'actioncolumn',
	       	renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
	            return html = '<a href="javascript:chooseCustomer(\'row5Panel\')" >选择客户</a>&nbsp;&nbsp;<a href="javascript:removeq(\'row5Panel\')">删除</a>';
	        }
       }];
		
		var cellEditing2 = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		
		var row_5=Ext.create('Ext.grid.Panel', {
			id:'row5Panel',
			titleAlign:'left',
			title:"新客户信息",
			minHeight:200,
			colspan:1,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : newGridStore2,
			columns : columns_5,
			plugins: [cellEditing2],
			tbar:[{text:'新增',iconCls:'icon-add',
				handler:function(){
					Ext.define('record', { 
			            extend: 'Ext.data.Model', 
			            fields: ["memberName","documentType","documentNumber","mobile"]
				    });
					var newCount=newGridStore2.getCount();
					if(newCount>=1){
						Ext.MessageBox.alert("系统提示","新客户信息只容许添加一条"); 
						return;
					}
				    var newFamilyMember  = new record(); 
				    newGridStore2.insert(0, newFamilyMember);
				    cellEditing2.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
			}
			},{ 
            	xtype: "checkboxgroup",
            	id:"ckYcustomerInfo",
            	name:"m_customerInfo",
            	items:[{
	            		boxLabel:'同原客户信息',
	            		inputValue:'1'
	            	}
                 ],
                listeners:{
                	'change' : function(obj,ischecked){
                		var ckStatusValue = Ext.getCmp('ckYcustomerInfo').getChecked();
                		var ckStatus="";
                		Ext.Array.each(ckStatusValue, function(item){
	  	        			ckStatus += item.inputValue;
	  	        		});
                		if(ckStatus==1){
        					var newCount=newGridStore2.getCount();
        					if(newCount>=1){
        						Ext.MessageBox.alert("系统提示","新客户信息只容许添加一条"); 
        						return;
        					}
        					var data;
        					if(gridStore4.getAt(0)){
        						data = gridStore4.getAt(0).data;
        					}else{
        						Ext.define('record', { 
            			            extend: 'Ext.data.Model', 
            			            fields: ["memberName","documentType","documentNumber","mobile"]
            				    });
        						data = new record();
        					}
        				    newGridStore2.insert(0, data);
        				    cellEditing2.startEditByPosition({
        				        row: 0, 
        				    	column: 0
        				    });
                		}else{
                			newGridStore2.removeAll();
                		}
                	}
                }
            }
			]
		});
		
	   var fromPanelInfo = Ext.create('Ext.form.FormPanel',{
		    renderTo:Ext.getBody(),
		    titleAlign:'center',
	        title:'更名审批单',
		    border: true,
		    layout:{
		    	 type: 'table',
                 columns: 2,
                 tableAttrs: {　　//在这儿控制table标签中的Attrs属性
                     border: 1,
                     cellpadding: 5,
                     cellspacing: 1,
                     width: '95%',
                     align: 'center',
                     style: "border:1px solid gray;border-collapse:collapse;margin:0 auto;text-align:center;"
                 },
                 tdAttrs: {　　//控制td标签的属性，以上用法都是在ext的api中查到，同样的方式可以给tr添加属性
                     width: '100px',
                     height: '40px',
                     style: "padding:5px",
                     valign: 'middle'
                 }
		    },
			 items:[{
				    xtype:'displayfield',
				    fieldLabel: '认购编号',
				    name: 'subscribeCode'
				},{
				    xtype:'displayfield',
				    fieldLabel: '业务类型',
				    value:'认购'
				},{
				    xtype:'displayfield',
				    fieldLabel: '房产名称',
				    name: 'roomName'
				},{
				    xtype:'displayfield',
				    fieldLabel: '客户姓名',
				    name: 'customerName'
				},{
				    xtype:'displayfield',
				    fieldLabel: '计价面积',
				    name: 'calculateArea'
				},{
				    xtype:'displayfield',
				    fieldLabel: '折前单价',
				    name: 'conversionPrice'
				},{
				    xtype:'displayfield',
				    fieldLabel: '折前总价',
				    name: 'lumpsumPrice'
				},{
				    xtype:'displayfield',
				    fieldLabel: '业务明细',
				    name: 'businessDetail'
				},row_4,row_5,row_2,row_3,{
				    xtype:'textarea',
				    fieldLabel: '更名原因',
				    name: 'remark',
				    width:780,
				    align: 'left',
				    id:'reason',
				    maxLength:255,
				    colspan:2,
				    allowBlank:false,
			    	blankText:'不能为空'
				},{
				    xtype:'displayfield',
				    fieldLabel: '经纪人',
				    name: 'userName'
				},{
				    xtype:'displayfield',
				    fieldLabel: '申请日期',
				    value: str
				},fileAttachment],
				dockedItems: [{
		            xtype: 'toolbar',
		            dock: 'bottom',
		            ui: 'footer',
		            layout: {
		                pack: 'center'
		            },
		            items: [{
		                minWidth: 80,
		                text: '提交审核',
		                id:'save_button',
		                iconCls:'icon-save',
		                handler:function(){
		                	var form = fromPanelInfo.getForm();
		               	    var familyMemberArray=[];
		               	    var newFamilyMemberArray=[];
		               	    var count=newGridStore.getCount();
		               	    var newCount=newGridStore2.getCount();
		            	    if(count<=0 && newCount<=0){
		            	    	 Ext.MessageBox.alert("系统提示","请添加新客户信息或者新共同购房者信息"); 
		            	    	 return;
		            	    }
		            	    for(var i=0;i<count;i++){
		            			//验证数据
		            	    	var documentNumber = newGridStore.getAt(i).data.documentNumber;
		            	    	if(documentNumber==null||documentNumber==""){
		            	    		 Ext.Msg.alert('提示', '请添加新客户证件号码!');
		            	    		 return;
		            	    	}else{
		            	    		 //验证手机号码的正确性
		       					 var userPhone = newGridStore.getAt(i).data.mobile;
			       					 if(userPhone!=null&&userPhone!=""){
//			       						 var regTel = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
//			       						 if(!regTel.test(userPhone)){
//			       							 Ext.Msg.alert('提示', '请输入正确的手机号码!');
//			       							 return;
//			       						 }
			       						 Ext.Ajax.request({
			    							url: contextPath+'/common/mobile/verifyingMobile',
			    							params: {
			    								mobile: userPhone,
			    							},
			    							method: 'POST',
			    							async: false,
			    							success: function(response){
			    								var text = Ext.decode(response.responseText);
			    								if(text.result=="1"){
			    									if(text.flag != "1"){
			    										Ext.Msg.alert('提示', '请输入正确的手机号码!');
			    		    							return;
			    									}
			    								}
			    							}
			    						 });
			       					 }else{
			       						 Ext.Msg.alert('提示', '请输入手机号码!');
			       						return;
			       					 }
		            	    		if(documentNumber.length>18){
		            	    			Ext.Msg.alert('提示', '请输入正确的证件号码!');
		            	    			return;
		            	    		}else{
		            	    			 familyMemberArray.push(Ext.JSON.encode(newGridStore.getAt(i).data));
		            	    		}
		            	    	}
		                	}
		            	    for(var i=0;i<newCount;i++){
		            	    	//验证数据
		            	    	var documentNumber = newGridStore2.getAt(i).data.documentNumber;
		            	    	if(documentNumber==null||documentNumber==""){
		            	    		 Ext.Msg.alert('提示', '请添加新客户证件号码!');
		            	    		 return;
		            	    	}else{
		            	    		 //验证手机号码的正确性
		       					 var userPhone = newGridStore2.getAt(i).data.mobile;
			       					 if(userPhone!=null&&userPhone!=""){
			       						 var regTel = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
//			       						 if(!regTel.test(userPhone)){
//			       							 Ext.Msg.alert('提示', '请输入正确的手机号码!');
//			       							 return;
//			       						 }
			       						 Ext.Ajax.request({
			    							url: contextPath+'/common/mobile/verifyingMobile',
			    							params: {
			    								mobile: userPhone,
			    							},
			    							method: 'POST',
			    							async: false,
			    							success: function(response){
			    								var text = Ext.decode(response.responseText);
			    								if(text.result=="1"){
			    									if(text.flag != "1"){
			    										Ext.Msg.alert('提示', '请输入正确的手机号码!');
			    		    							return;
			    									}
			    								}
			    							}
			    						 });
			       					 }else{
			       						 Ext.Msg.alert('提示', '请输入手机号码!');
			       						 return;
			       					 }
		            	    		if(documentNumber.length>18){
		            	    			Ext.Msg.alert('提示', '请输入正确的证件号码!');
		            	    			return;
		            	    		}else{
		            	    			newFamilyMemberArray.push(Ext.JSON.encode(newGridStore2.getAt(i).data));
		            	    		}
		            	    	}
		                	}
//		            	    console.log(familyMemberArray);
//		            	    console.log(newFamilyMemberArray);
		            	    
		                	if(form.isValid()){
		                		var fileUrlArr = fileAttachment.getFileArrs();
		                		var params={
		                				subscribeId:subscribeId,
			                			remark:Ext.getCmp("reason").getValue(),
			                			familyMember:familyMemberArray,
			                			newFamilyMember:newFamilyMemberArray,
			                			fileUrlArr:fileUrlArr,
			                			imageType: "6"
			                	};
		                		var resultJson=Ext.JSON.encode(params);
		                		Ext.getCmp("save_button").setVisible(false);
		                		Ext.Ajax.request({
			                		url:contextPath+'/customer/subscribe/submitChangeName',
			                		params:{
			                			params:resultJson,
			                			token: token
			                		},
			                		callback: function (options, success, response) {
			                			 var obj = JSON.parse(response.responseText);
			                			 if(obj.res=="1"){ 
			    							 Ext.MessageBox.confirm("提示","提交成功",function(btn,txt){
			    								 	Ext.getCmp("save_button").setVisible(false);
			    							    	if(btn=="yes"){
			    							    		 var tabKey = "cgn_"+subscribeId;
			    										 parent.TabControlRemove(tabKey);
			    							        }
			    							 });
			    						 }else{
			    							 Ext.getCmp("save_button").setVisible(true);
			    							 token = obj.obj;
			    							 Ext.MessageBox.alert("系统提示",obj.resMsg); 
			    						 }
			                		}
			                	});
		                		
		                	}
		                }
		            },
		            {
						xtype: "button",
						text : "返回",
						id: "btn_back",
						name: "btn_back",
						icon : contextPath + '/resources/ExtJSicons/shape_move_backwards.png',
						listeners: {
							click: function(){
								 var tabKey = "cgn_"+subscribeId;
								 parent.TabControlRemove(tabKey);
							}
						}
					}]
		        }
		        ]
	   });
	   
	   fromPanelInfo.getForm().load({
			url:contextPath+'/customer/subscribe/loadSubscribeInfo',
			params:{'subscribeId':subscribeId},
			success:function(form, action){
				var obj = action.result.data;
				var result=Ext.JSON.decode(obj);
				fromPanelInfo.getForm().setValues(result);
				var showUrl = "/customer/subscribe/toView?id="+subscribeId+"&returnUrl=,marketing,pin,index&processFlag=processHistoryShow";
				var herf = "<a href='javascript:parent.openMenu(\"0\",\""+subscribeId+"\",\"\",\"认购详情\",\""+showUrl+"\")' style='cursor:pointer'>业务明细</a>";
				fromPanelInfo.getForm().findField("businessDetail").setValue(herf);
			},   
			failure: function(form, action) {
		        Ext.Msg.alert("加载失败", action.result.errorMessage);
		    }

		});
	  
});